package com.ruoyi.tenant.interceptor;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.datasource.DynamicDataSource;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.goods.mapper.ShangpinxinxiMapper;
import com.ruoyi.goods.service.IShangpinxinxiService;
import com.ruoyi.tenant.domain.SysTenant;
import com.ruoyi.tenant.service.ISysTenantService;
import com.ruoyi.tenant.utils.AddDataSourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 租户数据源拦截器
 * @author Yu
 * @date 2023-06-30
 */

@Component
public class DateSourceInterceptor implements HandlerInterceptor {

    @Autowired
    private ISysTenantService iSysTenantService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private AddDataSourceUtil addDataSourceUtil;

//    public static final Logger log = LoggerFactory.getLogger(DateSourceInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tenantid = null;
        String uri = request.getRequestURI();
        List<String> tenantIdMethod = Arrays.asList("/login","/initdatabase/inittable","/sendSmsCode","/forgotPwd","/subForgotPwd");
        //登录和创建租户初始化表从reqbody拿租户ID
       if(tenantIdMethod.contains(uri)) {
           // 直接从HttpServletRequest的Reader流中获取RequestBody
           BufferedReader reader = request.getReader();
           StringBuilder builder = new StringBuilder();
           String line = reader.readLine();
           while (line != null) {
               builder.append(line);
               line = reader.readLine();
           }
           reader.close();
           String reqBody = builder.toString();
           JSONObject reqbody = JSONObject.parseObject(reqBody);
           tenantid = reqbody.getString("tenantId").toLowerCase();
           if(StringUtils.isEmpty(tenantid)){
               throw new RuntimeException("请输入租户ID");
           }
       }else {
           LoginUser user = tokenService.getLoginUser(request);
           tenantid = user.getTenantId().toLowerCase();
       }
       //主库直接放行
       if("master".equals(tenantid)){
           //设置主数据库
           DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER.name());
           return true;
       }

       //先查租户状态 只查状态
        Integer state = iSysTenantService.selectTenantStateByTenantId(tenantid);
        if (state == null) {
            throw new RuntimeException("无此租户:"+tenantid );
        }else if(state==1){
            throw new RuntimeException("租户["+tenantid+"]已停用" );
        }

        //获取连接池中所有链接
        DynamicDataSource dynamicDataSource = SpringUtils.getBean("dynamicDataSource");
        Map<Object, javax.sql.DataSource> resolvedDataSourcesMap = dynamicDataSource.getResolvedDataSources();
        Set<Object> dynamicDataSourceSet = resolvedDataSourcesMap.keySet();
        //若数据连接池没有则添加
        if (!dynamicDataSourceSet.contains(tenantid)) {
            SysTenant sysTenant = iSysTenantService.selectTenantByTenantId(tenantid);
            addDataSourceUtil.addDataSource(sysTenant);
        }
       //设置当前租户对应的数据库
       DynamicDataSourceContextHolder.setDataSourceType(tenantid);
//     log.info("当前数据源是:" + DynamicDataSourceContextHolder.getDataSourceType());

       return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        DynamicDataSourceContextHolder.clearDataSourceType();
    }


}
